import pickle
import base64
import os
import sys
import GetPasswd
from PyQt5.QtWidgets import *
import subprocess
import DialogResult
import configparser

class PasswdManager(object):
    def __init__(self):
        pass

    def save_encode_func(self, passwd):
        passwd_bt = passwd.encode("utf-8")
        target = base64.b64encode(passwd_bt)
        file = open('passwd_manager.pickle', 'wb')
        pickle.dump(target, file)
        file.close()

    def show_message(self, msg):
        dialog_result = QDialog()
        result_ui = DialogResult.Ui_Dialog()
        result_ui.setupUi(dialog_result)
        result_ui.label.setText(msg)

        if dialog_result.exec() == QDialog.Accepted:
            print(msg)
            return

    def read_decode_func(self):
        with open('passwd_manager.pickle', 'rb') as file:
            read_passwd = pickle.load(file)
        passwd = base64.b64decode(read_passwd)
        origin_passwd = passwd.decode("utf-8")
        return origin_passwd


    def get_passwd(self):
        dialog_get_passwd = QDialog()
        self.get_passwd_ui = GetPasswd.Ui_Dialog()
        self.get_passwd_ui.setupUi(dialog_get_passwd)
        # self.get_passwd_ui.lineEdit.setText(subprocess.getstatusoutput("whoami")[1])

        if_pass_ok = False
        try_times = 0
        while not if_pass_ok and try_times < 5:

            if (dialog_get_passwd.exec() == QDialog.Accepted):

                passwd = self.get_passwd_ui.lineEdit_2.text().strip()

                # check if passwd is ok, or, need to relogin
                ret = subprocess.getstatusoutput("echo " + passwd + " | sudo -S echo abc ")
                if ret[0] == 0:
                    self.save_encode_func(passwd)
                    return

                else:
                    self.do_passwd_wrong()
            else:
                sys.exit(0)

            try_times += 1

        language = self.get_passwd_ui.comboBox.currentText()
        if language == "English":
            self.show_message("try too many times, exit.")
        else:
            self.show_message("尝试了太多次，自动退出。")
        sys.exit(0)

    def do_passwd_wrong(self):
        language = self.get_passwd_ui.comboBox.currentText()
        if language == "English":
            self.show_message("do you add sudo for the current user? \nno sudo right or passwd wrong, please retry.")
        else:
            self.show_message("给当前用户添加了sudo权限了吗？\n 没有sudo权限或者您的密码错误，请重试。")
